Old trick to use state on web pages without any js
Toggle something on a Web page without JS
If you are gaining experience in CSS and trying the limits of CSS, this trick will make you think CSS more powerful than ever before. Some years ago I learned this trick from
We all know how you can use transitions and hover to change state of a element to create some interactivity. What if I told you you can make it toggle instead of temporarily changing state.
Labels and inputs
To understand this trick, first thing you should know is <input>
tags are binded to their labels with id
and for
properties.
Lets say you have a text input with id="mytext"
, when you click on a <label>
with for="mytext"
it behaves just like you clicked <input>
.
Checkbox
So in our case we will be using a <input>
with type="checkbox
to toggle stuff. And toggler will be a <label>
with for="[id of input]"
.
:checked state
In css we have a pseudo selector :checked
. It applies some styles only when a <input type="checkbox">
is checked. This allows us to apply some styles with permanent states not only to <input>
itself, but also its siblings and children.
However <input>
tags cant have any children. Here we use these CSS selectors to enhance our selection; ~
.
~ Selector
For example if we had a html like this:
<div>
<div class="key">key</div>
<div></div>
<div></div>
<div class="lock">lock</div>
</div>
<div>
<div></div>
<div></div>
<div></div>
<div class="lock">lock</div>
</div>
We could select only first <div>
with class "lock" with this selector.
.key~.lock{
color: red;
}
See example here:
Once we select a element after some sibling, we can also select children of selection which is handy because we can make this our main wrapper on page and toggle any styles on our page with this stateful selector.
Here is an example on Codepen demonstrating it:
Also you can go wild it like in below example:
If you check above examples code you will see it has a html soup.
You probably would use this trick only for navigation sidebars, modals etc.